package cn.buddha.jesj.loop;

import org.springframework.util.StopWatch;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName LoopTest
 * @Author 友野浩二
 * @Description 循环性能测试
 * @Version 1.0
 */
public class LoopTest {

    private static final Integer sourceSize = 1000;

    public static void main(String[] args) {
        // 测试源
        List<Integer> sourceList = new ArrayList<>();
        for (int i = 0; i < sourceSize; i++) {
            sourceList.add(i);
        }
        int sourceListSize = sourceList.size();
        System.out.println("测试源数据条数: " + sourceListSize);

        StopWatch stopWatch = new StopWatch();// 定义计时器

        // 1- 普通for循环
        stopWatch.start("1- 普通for循环");
        for (int i = 0; i < sourceListSize; i++) doSome(i);
        stopWatch.stop();

        // 2- 增强for循环
        stopWatch.start("2- 增强for循环");
        for (Integer integer : sourceList) doSome(integer);
        stopWatch.stop();

        stopWatch.start("3- forEach循环");
        sourceList.forEach(LoopTest::doSome);
        stopWatch.stop();

        stopWatch.start("4- forEach-stream串行流循环");
        sourceList.stream().forEach(LoopTest::doSome);
        stopWatch.stop();

        stopWatch.start("5- forEach-parallelStream并行流循环");
        sourceList.parallelStream().forEach(LoopTest::doSome);
        stopWatch.stop();

        System.out.println(stopWatch.prettyPrint());// 按照指定格式打印出一组任务耗时
        /*
         * 测试源数据条数: 1000
         * StopWatch '': running time (millis) = 4936
         * -----------------------------------------
         * ms     %     Task name
         * -----------------------------------------
         * 01251  025%  1- 普通for循环
         * 01198  024%  2- 增强for循环
         * 01144  023%  3- forEach循环
         * 01076  022%  4- forEach-stream串行流循环
         * 00267  005%  5- forEach-parallelStream并行流循环
         *
         * 结论: 如果循环里面做了一波事情,那么stream的并行流还是很省时的,因为其内部使用了多线程来执行
         **/
    }

    private static void doSome(int a) {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
